package com.atguigu.day05;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;

/**
 * @description :
 * @autor :lyh
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 设置每隔1分钟插入一次水位线
        env.getConfig().setAutoWatermarkInterval(60 * 1000L);

        env
                // nc -lk 9999
                // a 1
                // a 2
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Event>() {
                    @Override
                    public Event map(String in) throws Exception {
                        String[] array = in.split(" ");
                        return new Event(
                                array[0],
                                Long.parseLong(array[1]) * 1000L //转换毫秒单位
                        );
                    }
                })
                // 在map出来的数据流中插入水位线事件
                // 默认每隔200ms插入一次
                .assignTimestampsAndWatermarks(
                        // 设置最大延迟时间为5秒钟（Duration.ofSeconds(5)）
                        WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        // 告诉flink哪一个字段是事件时间
                                        return element.eventTimestamp;
                                    }
                                })
                )
                .keyBy(r -> r.key)
                // 定义大小为10秒钟的事件时间滚动窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .process(new WindowResult())
                .print();

        env.execute();
    }

    public static class Event {
        public String key;
        public long eventTimestamp;

        public Event() {
        }

        public Event(String key, long eventTimestamp) {
            this.key = key;
            this.eventTimestamp = eventTimestamp;
        }

        @Override
        public String toString() {
            return "key: " + key + ", eventTime: " + new Timestamp(eventTimestamp);
        }
    }

    public static class WindowResult extends ProcessWindowFunction<Event, String, String, TimeWindow> {

        @Override
        public void process(String s, ProcessWindowFunction<Event, String, String, TimeWindow>.Context context, Iterable<Event> elements, Collector<String> out) throws Exception {
            out.collect("窗口" + context.window().getStart() + "~" + context.window().getEnd() + "有：" +
                    "" + elements.spliterator().getExactSizeIfKnown() + " 条数据");
        }
    }
}
